package net.avcompris.binding.json.impl;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;

import javax.xml.parsers.ParserConfigurationException;

import net.avcompris.binding.BindConfiguration;
import net.avcompris.binding.dom.DomBinder;
import net.avcompris.binding.dom.impl.DefaultDomBinder;
import net.avcompris.binding.impl.AbstractBinder;
import net.avcompris.binding.json.JsonBinder;

import org.w3c.dom.Node;

	/**
	 * default implementation of {@link JsonBinder} by use of the <tt>avc-binding-dom</tt> toolset:
	 * First we transform the JSON incoming document into a DOM node, then we bind it to Java proxies.
	 *
	 * @author David Andrianavalontsalama
	 */
	public class DomJsonBinder extends AbstractBinder<Object> implements JsonBinder {

		@Override
		protected <T> T bindInterface(final BindConfiguration configuration,
				final Object json, final ClassLoader classLoader,
				final Class<T> clazz) {

			nonNullArgument(clazz, "clazz");
			nonNullArgument(json, "json");
			nonNullArgument(configuration, "configuration");
			nonNullArgument(classLoader, "classLoader");

			final Node node;

			try {

				node = DomJsonConverter.jsonToNode(json, configuration);

			} catch (final ParserConfigurationException e) {

				throw new DomJsonConversionException(
						"Cannot convert JSON document to DOM node", e);
			}

			final DomBinder domBinder = new DefaultDomBinder();

			return domBinder.bind(configuration, node, classLoader, clazz);
		}
	}
